//
//  SINASINAStuActivityAddTargetLevelViewController.m
//  PlanTech
//
//  Created by  androidlongs on 2018/6/28.
//  Copyright © 2018年  androidlongs. All rights reserved.
// 添加小目标

#import "SINASINAStuActivityAddTargetLevelViewController.h"
#import "SINAStuActivityTargetModel.h"
#import "SINAActivityTargetTableViewCell.h"
#import "SINAStuActivityAddTargetInputViewController.h"
#import "SINAActivityTargetDesViewController.h"
#import "SINACalendarUtils.h"

@interface SINASINAStuActivityAddTargetLevelViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic)  UITableView *mainContentTableView;
@property(nonatomic,strong) NSMutableArray *dataList;

@property(nonatomic,assign) NSInteger pageIndex;

@end

@implementation SINASINAStuActivityAddTargetLevelViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initViewFunction];
    
}
-(void)viewWillAppear:(BOOL)animated{
    [self loadingNetData];
}

-(void)initViewFunction{
    self.view.backgroundColor = [UIColor colorWithHexString:@"#f5f5f5"];
    self.navigationItem.title=@"小目标";
    self.mainContentTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 6, mainW, mainH-80)];
    [self.view addSubview:self.mainContentTableView];
    self.mainContentTableView.delegate=self;
    self.mainContentTableView.dataSource=self;
    self.mainContentTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.mainContentTableView.backgroundColor=[UIColor colorWithHexString:@"#f5f5f5"];
    self.mainContentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    //下拉刷新
    self.mainContentTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadingNewData)];
    //上拉刷新
    self.mainContentTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadingMoreData)];
    
    //自动更改透明度
    self.mainContentTableView.mj_header.automaticallyChangeAlpha = YES;
    
    //进入刷新状态
    //[self.mainContentTableView.mj_header beginRefreshing];
    
    [self.mainContentTableView.mj_header setBackgroundColor:[UIColor colorWithHexString:@"#eeeeee"]];
    [self.mainContentTableView.mj_footer setBackgroundColor:[UIColor colorWithHexString:@"#eeeeee"]];
    // Do any additional setup after loading the view from its nib.
    
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//下拉刷新
-(void) loadingNewData{
    
    
    
    
    //结束头部刷新
    [self.mainContentTableView.mj_header endRefreshing];
    [self.dataList removeAllObjects];
    [self.mainContentTableView reloadData];
    [self loadingNetData];
}

//上拉加载更多
-(void) loadingMoreData{
    
    //    __weak typeof(self) weakSelf = self;
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    //        //结束尾部刷新
    //        [weakSelf.mainContentTableView.mj_footer endRefreshing];
    //    });
    
    //    [self.dataList removeAllObjects];
    //    [self.mainContentTableView reloadData];
    //    [self.mainContentTableView.mj_footer endRefreshing];
    //    [self loadingNetData];
    
    __weak typeof(self) weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //结束头部刷新
        [weakSelf.mainContentTableView.mj_footer endRefreshing];
        
        [YPXToastView showToastViewWithText:@"暂无更多消息数据" andDuration:2 andParentView:weakSelf.view];
    });
}
-(NSMutableArray *)dataList{
    if (!_dataList) {
        _dataList = [NSMutableArray array];
    }
    return  _dataList;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataList.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    SINAActivityTargetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SINAActivityTargetTableViewCell"];
    
    if (cell == nil) {
        cell= [[[NSBundle mainBundle]loadNibNamed:@"SINAActivityTargetTableViewCell" owner:nil options:nil] firstObject];
        
    }
    
    
    SINAStuActivityTargetModel *model=self.dataList[indexPath.row];
    
    cell.cellTargetClickBlock = ^(NSInteger pos, SINAStuActivityTargetModel *itemModel) {
        //小目标查看详情
        if(itemModel.targetPageType==0){
            SINAActivityTargetDesViewController *desController = [[SINAActivityTargetDesViewController alloc]initWithNibName:@"SINAActivityTargetDesViewController" bundle:nil];
            desController.itemModel=itemModel;
            desController.activityModel=self.model;
            [self.navigationController pushViewController:desController animated:YES];
            
        }else{
            //添加小目标
            SINAStuActivityAddTargetInputViewController *inputController = [[SINAStuActivityAddTargetInputViewController alloc] initWithNibName:@"SINAStuActivityAddTargetInputViewController" bundle:nil];
            inputController .model  =  self.model;
            [self.navigationController pushViewController:inputController animated:YES];
        }
    };
    cell.activityModel =self.model;
    cell.model = model;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell ;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 86;
}
//查看详情
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
    //    NSInteger index = indexPath.row;
    //    SINAMsgItemModel * model = self.dataList[index];
    
    
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    //左滑删
    return YES;
}
// 进入编辑模式，按下出现的编辑按钮后,进行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        DLog(@"删除");
        SINAStuActivityTargetModel *model=self.dataList[indexPath.row];
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        [dict setObject:model.uuid forKey:@"uuid"];
        
        WISAlertView *alertView =  [[WISAlertView alloc]initWithTitle:@"提示" message:@"删除小目标？" sureBtn:@"确定" cancleBtn:@"取消"];
        alertView.resultIndex = ^(NSInteger index) {
            NSInteger activityStartTime = [self.model.activityStartTime integerValue];
            NSInteger activityEndTime = [self.model.activityStopTime integerValue];
            //当前时间
            NSInteger currentTime = [[SINACalendarUtils currentTimeStr] integerValue];
            
            if (currentTime<activityStartTime) {
                DLog(@"活动未开始");
            }else if(currentTime>=activityStartTime&&currentTime<=(activityEndTime)){
                DLog(@"活动中");
            }else if(currentTime>=activityEndTime&&currentTime<=(activityEndTime+30*60*1000)){
                //活动结束 以及结束后的半小时
            }else{
                //超时
                [YPXToastView showToastViewWithText:@"活动已结束 不可删除小目标" andDuration:2 andParentView:self.view];
                return ;
            }
            [self deleteTargetFunction:dict];
        };
        [alertView showXLAlertView];
        
        
    }
}

// 修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
    
}

/**
 *分页加载数据
 */
-(void)loadingNetData{
    
    
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    [dict setObject:[NSString stringWithFormat:@"%ld",(long)self.pageIndex] forKey:@"pageIndex"];
    [dict setObject:[NSString stringWithFormat:@"200"] forKey:@"pageSize"];
    [dict setObject:[NSString stringWithFormat:@"%@", [[SINACommonUserHelper share]getUserModel].userUid] forKey:@"receiveruuid"];
    
    [CXAFNHttpRequestUtils httpGetRequest:[NSString stringWithFormat:@"%@%@?organizeuuid=%@",baseUrl,userActivityTargetListUrl,self.model.activityUid] withParamters:dict success:^(id responseData) {
        
        [self.dataList removeAllObjects];
        NSString *code = responseData[@"code"];
        if ([code isEqualToString:@"1000"]) {
            NSMutableArray *result = responseData[@"content"];
            
            for (NSInteger i=0; i<result.count; i++) {
                NSDictionary *dict = result[i];
                SINAStuActivityTargetModel *model = [[SINAStuActivityTargetModel alloc]initWithDict:dict];
                [self.dataList addObject:model];
            }
            
        }else{
            NSString *message =responseData[@"message"];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定"
                                                                 cancleBtn:nil];
            [alertView showXLAlertView];
        }
        
        [self addItemFunction];
        [self.mainContentTableView reloadData];
        
    } failure:^(NSError *error, NSInteger errCode) {
        
        [YPXToastView showToastViewWithText:@"数据加载失败 网络异常" andDuration:2 andParentView:self.view];
        [self.dataList removeAllObjects];
        [self addItemFunction];
        [self.mainContentTableView reloadData];
        
    }];
}

//添加加载按钮
//活动结束前可以添加
-(void) addItemFunction{
    NSInteger activityStartTime = [self.model.activityStartTime integerValue];
    NSInteger activityEndTime = [self.model.activityStopTime integerValue];
    //当前时间
    NSInteger currentTime = [[SINACalendarUtils currentTimeStr] integerValue];
    
    if (currentTime<activityStartTime) {
        DLog(@"活动未开始");
    }else if(currentTime>=activityStartTime&&currentTime<=(activityEndTime)){
        DLog(@"活动中");
    }else if(currentTime>=activityEndTime&&currentTime<=(activityEndTime+30*60*1000)){
        //活动结束 以及结束后的半小时
    }else{
        //超时
        return;
    }
    
    
    SINAStuActivityTargetModel *model = [[SINAStuActivityTargetModel alloc]initWithDict:nil];
    model.targetPageType=1;
    [self.dataList addObject:model];
}

-(void) deleteTargetFunction:(NSMutableDictionary *) dict{
    
    
    [self startLoading];
    
    
    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
    [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
    WeakSelf;
    [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,userActivityTargetDeleteUrl] withParamters:dict2 success:^(id responseData) {
        NSString *code = responseData[@"code"];
        
        [weakSelf stopLoading];
        
        if ([code isEqualToString:@"1000"]) {
            //删除成功
            [YPXToastView showToastViewWithText:@"操作成功" andDuration:3 andParentView:self.view];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [weakSelf loadingNetData];
            });
        }else{
            NSString *message =responseData[@"message"];
            [YPXToastView showToastViewWithText:[NSString stringWithFormat: @"操作失败 %@" ,message] andDuration:3 andParentView:self.view];
        }
        
    } failure:^(NSError *error, NSInteger errCode) {
        
        [weakSelf stopLoading];
        [YPXToastView showToastViewWithText:@"操作失败 网络异常" andDuration:3 andParentView:self.view];
    }];
}

@end
